public class LC0443 {
    /**
     * 这个实际上就是游程编码
     * 时间复杂度：N，空间复杂度：1
     */
    public static int compress(char[] chars) {
        int length = chars.length;
        int writePtr = 0;
        char currentChar = chars[0];
        int count = 1; // 重复次数

        for (int i = 1; i < length; i++) {
            if (chars[i] == currentChar) count++;
            else {
                chars[writePtr++] = currentChar;
                // 长度复制到chars中
                if (count > 1) {
                    String countStr = Integer.toString(count);
                    for (int j = 0; j < countStr.length(); j++) {
                        chars[writePtr++] = countStr.charAt(j);
                    }
                }
                currentChar = chars[i];
                count = 1;
            }
        }
        // 处理最后一个字符
        chars[writePtr++] = currentChar;
        // 长度复制到chars中
        if (count > 1) {
            String countStr = Integer.toString(count);
            for (int j = 0; j < countStr.length(); j++) {
                chars[writePtr++] = countStr.charAt(j);
            }
        }

        return writePtr;
    }

    public static void main(String[] args) {
        char[] chars = new char[]{'a', 'a', 'b', 'b', 'c', 'c', 'c'};
        System.out.println(compress(chars));
    }
}
